package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/r3labs/sse/v2"
)

func main() {
	server := sse.New()

	mux := http.NewServeMux()
	// mux.HandleFunc("/events", backend.ServeHTTP)
	mux.HandleFunc("/events", func(w http.ResponseWriter, r *http.Request) {
		server.CreateStream("messages")

		go func() {
			for i := 0; i < 3; i++ {
				server.Publish("messages", &sse.Event{
					ID:   []byte(fmt.Sprintf("%d", i)),
					Data: []byte("ping"),
				})

				time.Sleep(time.Second)
			}

			server.Publish("messages", &sse.Event{
				Event: []byte("EOF"),
				// Retry     []byte
				// Comment   []byte
			})
		}()

		go func() {
			<-r.Context().Done()
			println("The client is disconnected here")
			return
		}()

		server.ServeHTTP(w, r)
	})

	err := http.ListenAndServe(":8080", mux)
	if err != nil {
		panic(err)
	}
}
